package com.hndfsj.app.datav;

import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.ServletContextResource;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hndfsj.framework.common.MReturnObject;
import com.hndfsj.framework.utils.HttpUtils;

public class DataVBaseController {
	static Logger log = LoggerFactory.getLogger(DataVBaseController.class);
	private Map<String, Date> lastRequestDates = new ConcurrentHashMap<String, Date>();
	private Map<String, String> jsonData = new ConcurrentHashMap<String, String>();

	public Date getLast(String url) {
		Date lastDate = lastRequestDates.get(url);
		return lastDate;
	}

	public void putCache(String key, String data) {
		if (StringUtils.isBlank(data)) {
			jsonData.put(key, data);
		}
	}

	public String getJsonData(String key) {
		return jsonData.get(key);
	}

	public boolean request(String url, int second) {
		Date lastDate = getLast(url);
		if (lastDate != null && (new Date().getTime() - lastDate.getTime()) > 1000 * second) {
			lastRequestDates.put(url, new Date());
			return false;
		}
		return false;
	}

	public String getData(String url) {
		return getData(url, false);
	}

	public String getData(String url, boolean remote) {
		if (remote) {
			return HttpUtils.doGet(url, "utf-8");
		} else {
			try {
				ServletContextResource resource = new ServletContextResource(
						((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
								.getServletContext(),
						"json/data.json");
				return JSON.parseObject(IOUtils.toString(resource.getInputStream(),"utf-8")).getString(url);
			} catch (IOException e) {
			}
			return "";
		}
	}

	public String parseServerData2JsonString(String url) {
		return parseServerData2JsonString(url,"respBody");
	}
	public String parseServerData2JsonString(String url,String key) {
		JSONObject json = JSON.parseObject(getData(url,true));
		if (MReturnObject.SUCCESS.equals(json.getString("respCode"))) {
			return json.getString(key);
		}
		return "";
	}

	public void writeJson(HttpServletResponse response, String json) {
		try {
			response.setContentType("application/json;charset=UTF-8");
			response.getWriter().write(json);
		} catch (IOException e) {
			log.error("", e);
		}
	}
}
